package cn.cuilan.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * Aop切面类
 *
 * @author zhangyue
 */
@Component
@Aspect
public class MethodExecuteTimeAspect {

    private final static Logger logger = LoggerFactory.getLogger(MethodExecuteTimeAspect.class);

    /**
     * 方法名
     */
    private String methodName;

    /**
     * 开始时间
     */
    private long startTime;

    /**
     * 结束时间
     */
    private long endTime;

    /**
     * 切入点
     */
    @Pointcut("execution(* cn.cuilan.controller..*(..))")
    public void controllerMethodPointcut() {
    }

    /**
     * 统计方法耗时前置通知
     *
     * @param joinPoint 可以访问连接点的细节
     */
    @Before("controllerMethodPointcut()")
    public void doBefore(JoinPoint joinPoint) {
        methodName = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        startTime = System.currentTimeMillis();
    }

    /**
     * 统计方法耗时后置通知
     */
    @After("controllerMethodPointcut()")
    public void doAfter() {
        endTime = System.currentTimeMillis() - startTime;
        logger.info("执行 " + methodName + " 耗时为：" + endTime + "ms");
    }

    /**
     * 统计方法耗时返回通知
     *
     * @param object 方法返回值
     */
    @AfterReturning(returning = "object", pointcut = "controllerMethodPointcut()")
    public void doAfterReturning(Object object) {
        logger.info("response = {}", object.toString());
    }

}
